//
//  AppDelegate.m
//  Hear
//
//  Created by mac on 2017/3/20.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "AppDelegate.h"
#import "AppDelegate+HRUmeng.h"
#import "YTKNetConfig.h"
#import "AppDelegate+HREase.h"
#import "AppDelegate+HRJSPush.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "HRLocationViewModel.h"
#import "HRLocationModel.h"
#import "HRUpdataUserInfoModel.h"
#import "HRAnswerListViewController.h"
#import <Harpy.h>
#import "FHHFPSIndicator.h"
#import "YTKApi.h"
@interface AppDelegate ()<CLLocationManagerDelegate,HarpyDelegate>
@property (nonatomic, strong) CLLocationManager * locationManager;
@property (nonatomic, strong)HRLocationViewModel *locationViewModel;
@property (nonatomic, copy)NSString *address;
@property (nonatomic, assign)BOOL isfirstLoadLoaction;
@property (nonatomic, assign)UIBackgroundTaskIdentifier bgTaskId;

@end

@implementation AppDelegate

- (HRLocationViewModel *)locationViewModel {
    if (_locationViewModel == nil) {
        _locationViewModel = [HRLocationViewModel new];
    }
    return _locationViewModel;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   
    // 配置Umeng
    [self setupUMeng];

#if DEBUG
    // 配置网络
    [YTKNetConfig config:SeverTEST];
#else
    [YTKNetConfig config:SeverRELEASE];
#endif
//    [YTKNetConfig config:SeverRELEASE];


    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    NSString *apnsCertName = @"";
    
    NSString *appkey = @"";
#if DEBUG
    apnsCertName = @"HearTestPush";
    appkey = @"1128170327115956#test";
#else
    apnsCertName = @"HearDevelepmentPush";
    appkey = @"1128170327115956#hear";
#endif
    
    [self easemobApplication:application
didFinishLaunchingWithOptions:launchOptions
                      appkey:appkey
                apnsCertName:apnsCertName
                 otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    
    [self ease_application:application didFinishLaunchingWithOptions:launchOptions];
   
    [self.window makeKeyAndVisible];
    
    
#if defined(DEBUG) || defined(_DEBUG)
    [[FHHFPSIndicator sharedFPSIndicator] show];
    
#endif
    
    self.isfirstLoadLoaction = YES;
    [self startLocation];
    
    [NSTimer scheduledTimerWithTimeInterval:600.f block:^(NSTimer * _Nonnull timer) {
        [self putLocationToServer];
    } repeats:YES];
 
    [self checkVersion];
    
    // JSPush
    [self setupJSPush];
    
    BOOL isProduction = NO;
#if DEBUG
    isProduction = NO;
#else
    isProduction = YES;
#endif
    [JPUSHService setupWithOption:launchOptions
                           appKey:@"a2f735adaf29ae9fea86348f"
                          channel:@"68db7c485feded959e099d44"
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];

    // 获取声音名片的文案配置
    [self getConfig];
    
    return YES;
}

#pragma mark 获取声音名片的文案配置
- (void)getConfig {
    YTKApi *api = [YTKApi apiGetWithUrl:@"App/Get_GetSoundCardConfig" para:nil];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            NSDictionary *dict = request.responseJSONObject;
            NSDictionary *bodyContentDict = [dict[@"BodyContent"] jsonValueDecoded];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"GuidingText"] forKey:@"GuidingText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"SampleText"] forKey:@"SampleText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"TipText"] forKey:@"TipText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"TextBoxTipText"] forKey:@"TextBoxTipText"];
            [[NSUserDefaults standardUserDefaults] setObject:bodyContentDict[@"TipTitleText"] forKey:@"TipTitleText"];
            DDLog(@"");
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        }];
    }];
}

#pragma mark ----开始定位
- (void)startLocation {
    if([CLLocationManager locationServicesEnabled]) {
        // 启动位置更新
        // 开启位置更新需要与服务器进行轮询所以会比较耗电，在不需要时用stopUpdatingLocation方法关闭;
        _locationManager = [[CLLocationManager alloc] init];
        //设置定位的精度
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        _locationManager.distanceFilter = 10.0f;
        _locationManager.delegate = self;
        if ([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0) {
            [_locationManager requestAlwaysAuthorization];
            [_locationManager requestWhenInUseAuthorization];
        }
        
        //开始实时定位
        [_locationManager startUpdatingLocation];
    } else {
        DDLog(@"请开启定位功能！");
    }
}

// 地理位置发生改变时触发
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
        DDLog(@"Longitude = %f", newLocation.coordinate.longitude);
        DDLog(@"Latitude = %f", newLocation.coordinate.latitude);
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",newLocation.coordinate.longitude] forKey:@"longitude"];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",newLocation.coordinate.latitude] forKey:@"latitude"];

        // 获取当前所在的城市名
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
        // 根据经纬度反向地理编译出地址信息
        [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error) {
             if (array.count > 0) {
                 CLPlacemark *placemark = [array objectAtIndex:0];
    
                 //将获得的所有信息显示到label上
                 DDLog(@"位置：%@",placemark.name);
                 DDLog(@"国家：%@",placemark.country);
                 DDLog(@"城市：%@",placemark.locality);
                 DDLog(@"区：%@",placemark.subLocality);
                 DDLog(@"街道：%@",placemark.thoroughfare);
                 DDLog(@"子街道：%@",placemark.subThoroughfare);
                 //获取城市
                 NSString *city = placemark.locality;
                 if (!city) {
                     //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                     city = placemark.administrativeArea;
                 }
                 NSString *provice = placemark.administrativeArea;
                 if (!provice) {
                     provice = city;
                 }
                 
                 self.address = [NSString stringWithFormat:@"%@,%@,%@",provice,city,placemark.subLocality,placemark.country];
                 [[NSUserDefaults standardUserDefaults] setObject:self.address forKey:@"address"];
                 DDLog(@"address =======%@%@%@%@%@",placemark.administrativeArea,city,placemark.subLocality,placemark.thoroughfare,placemark.subThoroughfare);
                 
                 if (self.isfirstLoadLoaction) {
                     self.isfirstLoadLoaction = NO;
                     [self putLocationToServer];
                 }

             } else if (error == nil && [array count] == 0) {
                 DDLog(@"No results were returned.");
             } else if (error != nil) {
                 DDLog(@"An error occurred = %@", error);
             }
         }];
    
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
}


- (void)putLocationToServer {
    if (![USERID length])return;
    HRLocationRequetModel *requstModel = [HRLocationRequetModel new];
    requstModel.LocalId = USERID;
    requstModel.Longitude = LONGITUDE; //@"121.686488"  专门为小贾提供
    requstModel.Latitude = LATITUDE;//@"31.180649" 
    requstModel.Address = self.address;
    requstModel.CreateTime = [self getCurrentTime];
    [self.locationViewModel putLoactionParam:requstModel isSeccess:^(BOOL isSeccess) {
        if (isSeccess) {
            self.isfirstLoadLoaction = NO;
        }
    }];
}

- (NSString *)getCurrentTime {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    //开启后台处理多媒体事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    AVAudioSession *session=[AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    //后台播放
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    //这样做，可以在按home键进入后台后 ，播放一段时间，几分钟吧。但是不能持续播放网络歌曲，若需要持续播放网络歌曲，还需要申请后台任务id，具体做法是：
    _bgTaskId = [AppDelegate backgroundPlayerID:_bgTaskId];
//    其中的_bgTaskId是后台任务UIBackgroundTaskIdentifier _bgTaskId;
}

+(UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId {
    //设置并激活音频会话类别
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    //允许应用程序接收远程控制
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    //设置后台任务ID
    UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
    newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:backTaskId];
    }
    return newTaskId;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    
    [application setApplicationIconBadgeNumber:unreadCount];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [self easemobApplication:application didReceiveRemoteNotification:userInfo];
    
    if([userInfo[@"from"] isEqualToString:@"JPush"]){
       [self getNewPushNotification:userInfo];
    }
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    if([userInfo[@"from"] isEqualToString:@"JPush"]){
        if (application.applicationState == UIApplicationStateBackground)
        [self getNewPushNotification:userInfo];
    }
    
    [JPUSHService handleRemoteNotification:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);

//    [VIEWCCONTROLER.navigationController pushViewController:[HRAnswerListViewController new] animated:YES];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[EMClient sharedClient] applicationWillEnterForeground:application];
    [[Harpy sharedInstance] checkVersion];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[Harpy sharedInstance] checkVersionDaily];//每天更新

}


- (void)applicationWillTerminate:(UIApplication *)application {
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    [self easamobApplication:application didReceiveLocalNotification:notification];
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    [self easemobApplication:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

#pragma mark - Harpy初始化
- (void)checkVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

    [self.locationViewModel getCheckVersion:@{@"ClientSymbol":@"1",@"ClientCurrentVersion":[infoDictionary objectForKey:@"CFBundleShortVersionString"],@"ClientUpdateUrl":@""} isForcedUpdate:^(BOOL isForcedUpdate) {

        dispatch_async(dispatch_get_main_queue(), ^{
            [[Harpy sharedInstance] setPresentingViewController:_window.rootViewController];
            [[Harpy sharedInstance] setDelegate:self];
            if (isForcedUpdate) {
                [[Harpy sharedInstance] setAlertType:HarpyAlertTypeForce];
            } else {
                [[Harpy sharedInstance] setAlertType:HarpyAlertTypeOption];
            }
            [[Harpy sharedInstance] setDebugEnabled:NO];
            [[Harpy sharedInstance] checkVersion];
        });
    }];
    
}



#pragma mark - HarpyDelegate
- (void)harpyDidShowUpdateDialog {
    DDLog(@"%s", __FUNCTION__);
}

- (void)harpyUserDidLaunchAppStore {
    DDLog(@"%s", __FUNCTION__);
}

- (void)harpyUserDidSkipVersion {
    DDLog(@"%s", __FUNCTION__);
}

- (void)harpyUserDidCancel {
    DDLog(@"%s", __FUNCTION__);
}

- (void)harpyDidDetectNewVersionWithoutAlert:(NSString *)message {
    DDLog(@"%@", message);
}

@end
